/*
 * @Description:用于处理sql语句
 * @Version: 2.0
 * @Autor: kafei
 * @Date: 2021-11-30 17:11:41
 * @LastEditors: kafei
 * @LastEditTime: 2021-12-21 13:51:55
 */
/**
 * @description: 用于查询语句
 * @param {目标列} targetTable
 * @param {参数对象} params
 * @param {模糊查询集合} like
 * @return {sql语句}
 * @author: kafei
 */
function createWhereSql(targetTable, params = {}, like = [], and = []) {
  let str = `select * from ${targetTable}`
  let resultStr = ''
  let isLike
  for (const key in params) {
    if (params[key] && `${params[key]}`.length > 0) {
      if (and.indexOf(key) > -1) {
        const target = params[key].split(',')
        isLike = `>'${target[0]}' and ${key}<'${target[1]}'`
      } else {
        isLike = like.indexOf(key) > -1 ? ` LIKE '%${params[key]}%'` : `='${params[key]}'`
      }
      resultStr += `${key}${isLike} and `
    }
  }
  if (resultStr.length > 0) {
    str += ' where ' + resultStr
    const len = str.length
    str = str.slice(0, len - 5)
  }
  return str
}

function createInsertSql(targetTable, data) {
  const sql = `INSERT INTO ${targetTable} `
  const keys = Object.keys(data)
  let keysStr = ''
  let valueStr = ''
  for (let i = 0; i < keys.length; i++) {
    const targer = keys[i]
    const spilt = `${i === keys.length - 1 ? '' : ','}`
    keysStr += `${targer}${spilt}`
    valueStr += `'${data[targer]}'${spilt}`
  }
  const resultSql = `${sql}(${keysStr}) VALUES (${valueStr})`
  return resultSql
}

module.exports = {
  createWhereSql,
  createInsertSql
}
